package cn.itcast.converters;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
//自定义的类型转换器
public class StringToDataConverter implements Converter<String, Date> {
    @Override
    public Date convert(String s) {
        //判断来源是否有值
        if(StringUtils.isEmpty(s)){
            throw new NullPointerException("Source can not be null!!!");
        }
        try{
            //定义类型转换器
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            //转换并返回
            Date date = dateFormat.parse(s);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
